import React, { useState, useCallback, useEffect } from 'react';
import { Input, Popover, InputNumber, Space, Typography, Button, Row, Col, Divider } from 'antd';
import { SketchPicker } from 'react-color';
import { BgColorsOutlined } from '@ant-design/icons';

interface ColorValue {
  hex: string;
  rgb: {
    r: number;
    g: number;
    b: number;
    a: number;
  };
}

interface ColorPickerProps {
  value?: string;
  onChange?: (color: string) => void;
  showAlpha?: boolean;
  size?: 'small' | 'middle' | 'large';
  presetColors?: string[];
  disabled?: boolean;
}

/**
 * 增强的颜色选择器组件
 * 支持透明度调整和预设颜色
 */
const ColorPicker: React.FC<ColorPickerProps> = ({
  value = '#000000',
  onChange,
  showAlpha = true,
  size = 'small',
  presetColors,
  disabled = false
}) => {
  const [open, setOpen] = useState(false);
  const [color, setColor] = useState<ColorValue>({
    hex: '#000000',
    rgb: { r: 0, g: 0, b: 0, a: 1 }
  });

  // 默认预设颜色
  const defaultPresetColors = [
    '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
    '#13c2c2', '#2f54eb', '#fa8c16', '#eb2f96', '#a0d911',
    '#ffffff', '#000000', '#f5f5f5', '#d9d9d9', '#434343',
  ];

  // 从外部value解析颜色
  useEffect(() => {
    if (!value) return;

    try {
      // 解析rgba格式
      if (value.startsWith('rgba')) {
        const rgba = value.match(/rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([.\d]+)\s*\)/);
        if (rgba) {
          const [, r, g, b, a] = rgba.map((v, i) => (i === 0 ? v : Number(v)));
          
          // 计算hex颜色
          const hex = '#' + [r, g, b].map(v => {
            const hex = Math.round(v).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
          }).join('');
          
          setColor({ hex, rgb: { r, g, b, a } });
          return;
        }
      }
      
      // 解析hex格式
      if (value.startsWith('#')) {
        const hex = value;
        setColor({ 
          hex, 
          rgb: { 
            r: parseInt(hex.slice(1, 3), 16),
            g: parseInt(hex.slice(3, 5), 16),
            b: parseInt(hex.slice(5, 7), 16),
            a: 1
          } 
        });
        return;
      }
    } catch (error) {
      console.error('解析颜色值失败', error);
    }
  }, [value]);

  // 处理颜色变化
  const handleColorChange = useCallback((colorValue: any) => {
    setColor(colorValue);
    
    if (onChange) {
      if (showAlpha && colorValue.rgb.a < 1) {
        const { r, g, b, a } = colorValue.rgb;
        onChange(`rgba(${r}, ${g}, ${b}, ${a})`);
      } else {
        onChange(colorValue.hex);
      }
    }
  }, [onChange, showAlpha]);

  // 处理透明度变化
  const handleAlphaChange = useCallback((alpha: number | null) => {
    if (alpha === null) return;
    
    const newColor = {
      ...color,
      rgb: {
        ...color.rgb,
        a: alpha
      }
    };
    
    setColor(newColor);
    
    if (onChange) {
      const { r, g, b, a } = newColor.rgb;
      onChange(`rgba(${r}, ${g}, ${b}, ${a})`);
    }
  }, [color, onChange]);

  // 判断是否为深色
  const isDarkColor = useCallback((hex: string) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return (r * 0.299 + g * 0.587 + b * 0.114) < 128;
  }, []);

  // 颜色选择面板内容
  const content = (
    <div style={{ width: 250 }}>
      <SketchPicker
        color={color.rgb}
        onChange={handleColorChange}
        presetColors={presetColors || defaultPresetColors}
        disableAlpha={!showAlpha}
        width="100%"
      />
      
      {showAlpha && (
        <>
          <Divider style={{ margin: '12px 0 8px 0' }} />
          <Space direction="vertical" style={{ width: '100%' }}>
            <Typography.Text style={{ fontSize: 12 }}>透明度</Typography.Text>
            <InputNumber
              size="small"
              value={color.rgb.a}
              onChange={handleAlphaChange}
              min={0}
              max={1}
              step={0.01}
              style={{ width: '100%' }}
            />
          </Space>
        </>
      )}
    </div>
  );

  // 颜色预览元素
  const colorPreview = (
    <div
      style={{
        width: '100%',
        height: 28,
        backgroundColor: value,
        borderRadius: 4,
        border: '1px solid #d9d9d9',
        cursor: disabled ? 'not-allowed' : 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        opacity: disabled ? 0.5 : 1
      }}
    >
      {value && isDarkColor(color.hex) && (
        <BgColorsOutlined style={{ color: '#fff' }} />
      )}
    </div>
  );

  return (
    <Popover
      content={content}
      trigger="click"
      open={!disabled && open}
      onOpenChange={setOpen}
    >
      {colorPreview}
    </Popover>
  );
};

export default ColorPicker;